import { Button, Form, FormInstance, Input, message, Modal, Switch, Table } from "antd";
import { ColumnProps } from "antd/lib/table";
import { useEffect, useMemo, useRef, useState } from "react";
import { createSource, deleteSource, getSource, updateSource } from "src/api";
import { PageData } from "src/util";
import { history } from "src/util/history";
import { MiniAppPageRecord } from "./MiniAppPageType";
import qs from "qs";

interface FormFields {
	name: string;
	link: string;
	status: 0 | 1;
}
const MiniAppPage = () => {
	const [pageList, setPageList] = useState<MiniAppPageRecord[]>([]);
	const [pageOptions, setPageOptions] = useState({ current: 1, pageSize: 10, total: 10 });
	const pageOptionsRef = useRef({ current: 1, pageSize: 10, total: 10 });
	const fetchData = async () => {
		const { data } = await getSource<PageData<MiniAppPageRecord[]>>({
			source: "pageSetting",
			page: pageOptionsRef.current.current,
			pageSize: pageOptionsRef.current.pageSize,
		});
		pageOptionsRef.current.total = Number(data?.total) || 10;
		setPageOptions({ ...pageOptionsRef.current });
		setPageList(data?.data || []);
	};
	useEffect(() => {
		fetchData();
	}, []);
	const columns = useMemo<ColumnProps<MiniAppPageRecord>[]>(
		() => [
			{
				dataIndex: "name",
				title: "页面名称",
			},
			{
				dataIndex: "status",
				title: "状态",
				render(status) {
					if (status === 0) {
						return "未发布";
					}
					if (status === 1) {
						return "已发布";
					}
				},
			},
			{
				dataIndex: "link",
				title: "页面链接",
			},
			{
				title: "操作",
				render(_, record) {
					return (
						<>
							<Button
								onClick={() => {
									operatePageType.current = "edit";
									operatedRecord.current = record;
									pageForm.current?.setFieldsValue(record);
									setModalVisible(true);
								}}
							>
								编辑
							</Button>
							<Button
								className="ml-2"
								type="primary"
								onClick={() => {
									history.push({ pathname: "/admin/miniApp/config", search: qs.stringify({ type: "edit", id: record._id }) });
								}}
							>
								配置
							</Button>
							<Button
								className="ml-2"
								danger
								onClick={async () => {
									deleteSource({ source: "page_setting", id: record._id });
									await fetchData();
									message.success("已删除");
								}}
							>
								删除
							</Button>
						</>
					);
				},
			},
		],
		[]
	);
	const [modalVisible, setModalVisible] = useState(false);
	const operatePageType = useRef<"add" | "edit">("add");
	const pageForm = useRef<FormInstance<FormFields>>(null);
	const operatedRecord = useRef<MiniAppPageRecord>();
	return (
		<>
			<Button
				type="primary"
				className="mb-2"
				onClick={() => {
					setModalVisible(true);
					operatePageType.current = "add";
					pageForm.current?.resetFields();
				}}
			>
				添加页面
			</Button>
			<Table
				columns={columns}
				dataSource={pageList.map((item, index) => ({ ...item, key: index }))}
				pagination={{
					...pageOptions,
					onChange(page, pageSize) {
						pageOptionsRef.current.current = page;
						pageOptionsRef.current.pageSize = pageSize;
						fetchData();
					},
				}}
			/>
			<Modal
				forceRender
				open={modalVisible}
				onOk={async () => {
					const formData = await pageForm.current?.validateFields();
					if (formData?.status !== undefined) formData.status = formData?.status ? 1 : 0;
					if (operatePageType.current === "add") {
						await createSource({ source: "page_setting", ...formData });
					}
					if (operatePageType.current === "edit") {
						if (!operatedRecord.current?._id) return message.error("页面id不存在");
						await updateSource({ source: "page_setting", ...formData, id: operatedRecord.current._id });
					}
					await fetchData();
					message.success(operatePageType.current === "edit" ? "编辑成功" : "添加成功");
					setModalVisible(false);
				}}
				onCancel={() => setModalVisible(false)}
				title={operatePageType.current === "add" ? "添加页面" : "编辑页面"}
			>
				<div className="mb-4" />
				<Form ref={pageForm} labelCol={{ span: 4 }}>
					<Form.Item name="name" label="页面名称" rules={[{ required: true, message: "请输入页面名称" }]}>
						<Input placeholder="请输入页面名称" />
					</Form.Item>
					<Form.Item name="link" label="页面链接" rules={[{ required: true, message: "请输入页面链接" }]}>
						<Input placeholder="请输入页面链接" />
					</Form.Item>
					<Form.Item name="status" label="状态" valuePropName="checked">
						<Switch checkedChildren="已发布" unCheckedChildren="未发布" />
					</Form.Item>
				</Form>
			</Modal>
		</>
	);
};

export default MiniAppPage;
